package org.exteen.output;

import java.io.Writer;

public class FlatExteenStream extends ExteenStream {

    public final static boolean DEFAULT_ESCAPE = true;
    public final static TrimType DEFAULT_TRIM = TrimType.NONE;
    
    private StringBuilder buffer = new StringBuilder();

    private boolean escape = DEFAULT_ESCAPE;
    private TrimType trimType;

    public static enum TrimType {
        NONE, FULL, SMART;
    }

    public FlatExteenStream(ExteenStream base) {
        super(base);
        if (base instanceof FlatExteenStream) {
            FlatExteenStream sourcebase = (FlatExteenStream) base;
            this.escape = sourcebase.escape;
            this.trimType = sourcebase.trimType;
        } else {
            this.trimType = DEFAULT_TRIM;
            this.escape = DEFAULT_ESCAPE;
        }
    }

    public FlatExteenStream(Writer writer, TrimType trimType) {
        super(writer);
        this.trimType = trimType;
        this.escape = DEFAULT_ESCAPE;
    }

    public void setEscape(boolean escape) {
        this.escape = escape;
    }

    public void setTrimType(TrimType trimType) {
        this.trimType = trimType;
    }

    public void flush() {
        if (buffer.length()>0) {

            String string = buffer.toString();
            if (trimType==TrimType.NONE) {
                this.writer.print(string);
            } else if (trimType==TrimType.FULL) { 
                this.writer.print(string.trim());
            } else {
                // should left 1 space if there are more
                String trimmed = string.trim();
                if (trimmed.length()==0) {
                    this.writer.print(" "); // there were some spaces
                } else {
                    // left
                    if (trimmed.charAt(0)!=string.charAt(0)) {
                        this.writer.print(" "); // there were some spaces on the left... so print 1 space
                    }
                    this.writer.print(trimmed);
                    // right
                    if (trimmed.charAt(trimmed.length() - 1) != string.charAt(string.length() - 1)) {
                        this.writer.print(" "); // there were some spaces on the right... so print 1 space
                    }
                }
            }
            buffer.setLength(0);
        }
    }

    public void printTagOpen(String tagName) {
        flush();
        super.printTagOpen(tagName);
    }

    public void printTagClose(String tagName) {
        flush();
        super.printTagClose(tagName);
    }

    public void printText(String string) {
        buffer.append(string);
    }

    public boolean isEscape() {
        return escape;
    }

    public TrimType getTrimType() {
        return trimType;
    }
}
